package cn.klaw.job.admin.controller;

import cn.klaw.job.admin.controller.annotation.PermissionLimit;
import cn.klaw.job.admin.core.conf.XxlJobAdminConfig;
import cn.klaw.job.admin.service.HandlerNameService;
import cn.klaw.job.core.biz.AdminBiz;
import cn.klaw.job.core.biz.model.HandleCallbackParam;
import cn.klaw.job.core.biz.model.RegistryParam;
import cn.klaw.job.core.biz.model.ReturnT;
import cn.klaw.job.core.util.GsonTool;
import cn.klaw.job.core.util.XxlJobRemotingUtil;
import cn.klaw.scheduletask.entity.HandlerNameEntity;
import cn.klaw.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.klaw.job.core.biz.model.RegistryHandlerName;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by xuxueli on 17/5/10.
 */
@Controller
@RequestMapping("/api")
public class JobApiController {

    @Resource
    private AdminBiz adminBiz;
    @Autowired
    private HandlerNameService handlerNameService;

    /**
     * api
     *
     * @param uri
     * @param data
     * @return
     */
    @RequestMapping("/{uri}")
    @ResponseBody
    @PermissionLimit(limit=false)
    public ReturnT<String> api(HttpServletRequest request, @PathVariable("uri") String uri, @RequestBody(required = false) String data) {

        // valid
        if (!"POST".equalsIgnoreCase(request.getMethod())) {
            return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, HttpMethod not support.");
        }
        if (uri==null || uri.trim().length()==0) {
            return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping empty.");
        }
        if (XxlJobAdminConfig.getAdminConfig().getAccessToken()!=null
                && XxlJobAdminConfig.getAdminConfig().getAccessToken().trim().length()>0
                && !XxlJobAdminConfig.getAdminConfig().getAccessToken().equals(request.getHeader(XxlJobRemotingUtil.XXL_JOB_ACCESS_TOKEN))) {
            return new ReturnT<String>(ReturnT.FAIL_CODE, "The access token is wrong.");
        }

        // services mapping
        if ("callback".equals(uri)) {
            List<HandleCallbackParam> callbackParamList = GsonTool.fromJson(data, List.class, HandleCallbackParam.class);
            return adminBiz.callback(callbackParamList);
        } else if ("registry".equals(uri)) {
            RegistryParam registryParam = GsonTool.fromJson(data, RegistryParam.class);
            return adminBiz.registry(registryParam);
        } else if ("registryRemove".equals(uri)) {
            RegistryParam registryParam = GsonTool.fromJson(data, RegistryParam.class);
            return adminBiz.registryRemove(registryParam);
        } else {
            return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping("+ uri +") not found.");
        }

    }

    /**
     * api
     *
     * @param data
     * @return
     */
    @RequestMapping("/{uri}/handlerName")
    @ResponseBody
    @PermissionLimit(limit=false)
    public ReturnT<String> registryHandler(@PathVariable("uri") String uri, @RequestBody(required = false) String data) {
        RegistryHandlerName handlerName = JsonUtil.getJsonToBean(data, RegistryHandlerName.class);
        if (handlerName != null) {
            for (String hand : handlerName.getHandlerList()) {
                HandlerNameEntity entity = new HandlerNameEntity();
                entity.setExecutor(handlerName.getExecutorName());
                entity.setHandlerName(hand);
                // 注册前先删除
                handlerNameService.delete(entity);
                if (!"remove".equals(uri)) {
                    handlerNameService.create(entity);
                }
            }
        }
        return new ReturnT<>(ReturnT.SUCCESS_CODE, "处理成功");
    }

}
